package com.jushu.storbox.view.dialog;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;

import com.jushu.storbox.util.LogUtil;

/***
 * 
 * Common Dialog
 */
public class PopupMenuWindow {
	private final static String TAG = PopupMenuWindow.class.getSimpleName();
	private View conventView;
	PopupWindow popWindow = null;

	/**
	 * @param context
	 * @param width LayoutParamter.WRAP_CONTENT, MATCH_PARENT, xxdp,...
	 * @param height LayoutParamter.WRAP_CONTENT, MATCH_PARENT, xxdp,...
	 * @param resourceId R.layout.xxxx
	 */
	public PopupMenuWindow(Context context, int width, int height, int resourceId) {
		LogUtil.i(TAG, TAG);
		if (null == conventView) {
			conventView = LayoutInflater.from(context).inflate(resourceId, null);
			if(conventView != null) {
				onInflaterFinished(conventView);
			} else {
				LogUtil.e(TAG,"inflater the xml error");
			}
		}
		
		if(conventView != null) {
			popWindow = new PopupWindow(conventView, width, height, true);
			popWindow.setBackgroundDrawable(new ColorDrawable(0x00FFFFFF));
			popWindow.setFocusable(true);
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
				popWindow.setOverlapAnchor(true);
			}
			popWindow.setOutsideTouchable(true);
		}
	}

	public final void showAtLocation(View parent, int gravity, int offsetX, int offsetY) {
		if(popWindow != null) {
			popWindow.showAtLocation(parent, gravity, offsetX, offsetY);
		}
	}

	@RequiresApi(api = Build.VERSION_CODES.KITKAT)
	public final void showAsDropDown(View parent, int gravity, int offsetX, int offsetY) {
		if(popWindow != null) {
			popWindow.showAsDropDown(parent,  offsetX, offsetY, gravity);
		}
	}


	public void setOnDismissListener(OnDismissListener onDismissListener) {
		popWindow.setOnDismissListener(onDismissListener);;
	}
	
	public final int getWidth() {
		if(popWindow != null) {
			return popWindow.getWidth();
		} else {
			return 0;
		}
	}
	
	public final int getHeight() {
		if(popWindow != null) {
			return popWindow.getHeight();
		} else {
			return 0;
		}
	}

	public final void dismiss() {
		if(popWindow != null) {
			popWindow.dismiss();
		}
	}
	
	public final boolean isShowing() {
		if(popWindow != null) {
			return popWindow.isShowing();
		} else {
			return false;
		}
	}
	
	protected void onInflaterFinished(View contentView) {
	}
}
